'use client';

import { useEffect, useState, useRef } from 'react';
import { useSearchParams } from 'next/navigation';
import dayjs from 'dayjs';
import { getUrlParams } from '@/api/baseInfo';
import styles from './style.module.scss';

export default function Home() {

  const searchParams = useSearchParams();
  /** 轮播时间 */
  const timer = searchParams.get('timer');
  /** 是否自动轮播 */
  const autoCarousel = !!timer;

  const [srcList, setSrcList] = useState<string[]>([]);
  const [current, setCurrent] = useState(0);
  const [direction, setDirection] = useState('down');
  const srcListLength = useRef(0);

  /** 手动控制 */
  const handleKeyDown = (e: KeyboardEvent) => {
    if (e.key === 'ArrowUp') {
      setDirection('up');
      setCurrent((current) =>
        current === 0 ? srcListLength.current - 1 : current - 1,
      );
    } else if (e.key === 'ArrowDown') {
      setDirection('down');
      setCurrent((current) =>
        srcListLength.current - 1 === current ? 0 : current + 1,
      );
    }
  };

  let delayer: any = null;
  /** 自动轮播 */
  const handleAutoCarousel = () => {
    if (delayer) {
      clearTimeout(delayer);
      delayer = null;
    }
    delayer = setTimeout(
      () => {
        setDirection('down');
        setCurrent((current) =>
          srcListLength.current - 1 === current ? 0 : current + 1,
        );
        handleAutoCarousel();
      },
      timer ? Number(timer) : 30000,
    );
  };

  let reTimer: any = null;
  /** 定时刷新页面 */
  const reloadPage = () => {
    if (reTimer) {
      clearTimeout(reTimer);
      reTimer = 0;
    }

    if (typeof window === 'undefined') {
      return;
    }

    reTimer = setTimeout(() => {
      const date = dayjs().format('HH:mm:ss');
      if (date === '08:30:00' || date === '12:30:00') {
        window.location.reload();
      }
      reloadPage();
    }, 1000);
  };

  const getUrlPathParams = (regex: any) => {
    let paramsArr = [];
    let path = '';
    if (typeof window === 'undefined') {
      return;
    }
    while (
      (paramsArr = regex.exec(decodeURIComponent(window.location.href))) !==
      null
    ) {
      path = paramsArr[1];
    }

    return path;
  };

  const getUrlList = () => {
  
  

      let urls = [];
      // if (videoTime) {
      //   const params = new URLSearchParams(gylObg).toString();
      //   urls.push(
      //     location.origin.includes('localhost') ||
      //       location.origin.includes('192.168.12.49')
      //       ? `${location.origin}/global?${params}`
      //       : `${location.origin}/dashboard-monitor/global.html?${params}`,
      //   );
      // }

      const shippingPathRegex = /shippingPath=\{\{(.*?)\}\}/g;
      const earthPathRegex = /earthPath=\{\{(.*?)\}\}/g;
      const ybdPathRegex = /ybdPath=\{\{(.*?)\}\}/g;
      const psjPathRegex = /psjPath=\{\{(.*?)\}\}/g;
      // 商城六期仓页面
      const cg06PathRegex = /cg06Path=\{\{(.*?)\}\}/g;

      let shippingPath = getUrlPathParams(shippingPathRegex);
      let earthPath = getUrlPathParams(earthPathRegex);
      let ybdPath = getUrlPathParams(ybdPathRegex);
      let psjPath = getUrlPathParams(psjPathRegex);
      let cg06Path = getUrlPathParams(cg06PathRegex);
      // console.log(
      //   shippingPath,
      //   earthPath,
      //   ybdPath,
      //   psjPath,
      //   getUrlParams('token'),
      //   'shippingPathshippingPathshippingPath',
      // );

      const iToken = getUrlParams('token');

      if (earthPath) {
        earthPath = earthPath.includes('?')
          ? `${earthPath}&access_token=${iToken}`
          : `${earthPath}?access_token=${iToken}`;
        urls.push(earthPath);
      }
      if (shippingPath) {
        shippingPath = shippingPath.includes('?')
          ? `${shippingPath}&access_token=${iToken}`
          : `${shippingPath}?access_token=${iToken}`;
        urls.push(shippingPath);
      }

      if (ybdPath) {
        ybdPath = ybdPath.includes('?')
          ? `${ybdPath}&access_token=${iToken}`
          : `${ybdPath}?access_token=${iToken}`;
        urls.push(ybdPath);
      }

      if (psjPath) {
        urls.push(psjPath);
      }
      if (cg06Path) {
        cg06Path = cg06Path.includes('?')
          ? `${cg06Path}&access_token=${iToken}`
          : `${cg06Path}?access_token=${iToken}`;
        urls.push(cg06Path);
      }
      setSrcList(urls);
      srcListLength.current = urls.length;
      // decryptData(data.monitorServerPassword, data.monitorServerSecret);
  };

  useEffect(() => {
    getUrlList();
    if (autoCarousel) {
      handleAutoCarousel();
    }
    reloadPage();
    window.addEventListener('keydown', handleKeyDown);
    return () => {
      window.removeEventListener('keydown', handleKeyDown);
      clearTimeout(delayer);
      clearTimeout(reTimer);
    };
  }, []);


  return (
    <div style={{ backgroundColor: '#000', width: '100vw', height: '100vh' }}>
      {srcList.map((i: string, index: number) => (
        <div
          style={{
            overflow: 'hidden',
            width: '100vw',
            height: '100vh',
            position: 'absolute',
            top: 0,
            left: 0,
            display: index === current ? 'block' : 'none',
          }}
          className={
            index === current
              ? styles[
                  direction === 'up' ? 'bounce-enter-active' : 'up-enter-active'
                ]
              : styles[
                  direction === 'up' ? 'bounce-leave-active' : 'up-leave-active'
                ]
          }
          key={i}
        >
          <iframe
            src={i}
            id={'iframe' + index}
            style={{ width: '100vw', height: '100vh', pointerEvents: 'none', position: 'absolute', top: 0, left: 0 }}
            frameBorder="0"
          />
        </div>
      ))}
    </div>
  );
}
